package com.ruoyi.web.controller.tool;

import java.util.Random;
import java.util.concurrent.*;

public class CallableAndFuture {

    public static void main(String[] args) {

        //生成线程池大小20
        ExecutorService executorService = Executors.newFixedThreadPool(20);

        CompletionService<String> completionService = new ExecutorCompletionService<String>(executorService);

        for (int i=0;i<20;i++){
            final int seq = i;

            completionService.submit(new Callable<String>() {
                @Override
                public String call() throws Exception {
                    Thread.sleep(new Random().nextInt(1000));
                    return "sequence of thread: " + seq;
                }
            });

        }

        // 获取返回结果
        for (int i=0; i<20; i++) {
            try {
                System.out.println(completionService.take().get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }


    }
}
